from ariadne import QueryType, make_executable_schema
from ariadne.asgi import GraphQL
import uvicorn
from tencent_api import Solutions
import datetime
from ariadne import ObjectType
import dbm
import json

today = datetime.datetime.now()

ss = Solutions()

type_defs = """
    #['InstanceId', 'InstanceName', 'OsName', 'PublicIpAddresses', 'PrivateIpAddresses', 'AccountName', 'CPU', 'Memory', 'Zone', 'ExpiredTime', 'InternetMaxBandwidthOut']
    type Server {
        PublicIpAddresses: String
        ExpiredTime: String
        ServerName: String
        AccountName: String
        InstanceId: String
        InstanceName: String
        OsName: String
        CPU: String
        Memory: String
        Zone: String
        InternetMaxBandwidthOut: String
        days_left: Int
    }

# ['DiskName', 'DiskSize', 'DiskUsage', 'AccountName', 'ExpiredTime'])
    type Disk {
        ExpiredTime: String
        DiskName: String
        DiskSize: String
        DiskUsage: String
        AccountName: String
        days_left: Int
    }

    type Query {
        hello(name: String! = "World"): String!
        refresh_servers: [Server!]
        servers: [Server!]
        refresh_disks: [Disk!]
        disks: [Disk!]
    }
"""

query = QueryType()


@query.field("hello")
def resolve_hello(_, info, name):
    return f"Hello, {name}!"


@query.field("refresh_servers")
def resolve_refresh_servers(_, info):
    servers = ss.get_all_server_simple()
    with dbm.open("tencent.db", "c") as db:
        db["servers"] = json.dumps(servers)
        db["servers_update_time"] = today.strftime("%Y-%m-%d %H:%M:%S")
        return servers


@query.field("servers")
def resolve_servers(_, info):
    # 创建或打开数据库
    with dbm.open("tencent.db", "c") as db:
        print(db.keys())
        print(db.get("servers_update_time"))
        print(db["servers"])
        return sorted(json.loads(db["servers"]), key=lambda x: x["days_left"])


@query.field("refresh_disks")
def resolve_refresh_disks(_, info):
    disks = ss.get_all_disk_simple()
    with dbm.open("tencent.db", "c") as db:
        db["disks"] = json.dumps(disks)
        db["disks_update_time"] = today.strftime("%Y-%m-%d %H:%M:%S")
        return disks


@query.field("disks")
def resolve_disks(_, info):
    # 创建或打开数据库
    with dbm.open("tencent.db", "c") as db:
        print(db.keys())
        print(db.get("disks_update_time"))
        print(db["disks"])
        return sorted(json.loads(db["disks"]), key=lambda x: x["days_left"])


schema = make_executable_schema(type_defs, query)
app = GraphQL(
    schema,
)

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7000)
